export const generateChallenge = (round, isTeamMode = false, selectedAI = null) => {
  const challengeTypes = [
    "reaction",
    "memory",
    "math",
    "pattern",
    "color",
    "logic",
    "word",
    "sequence",
    "spatial",
    "attention",
    "comparison",
    "calculation",
  ];

  // 根据AI对手的专长调整题目类型权重
  let weightedTypes = [...challengeTypes];
  if (selectedAI) {
    if (selectedAI.specialties.includes("逻辑推理")) {
      weightedTypes.push("logic", "sequence");
    }
    if (selectedAI.specialties.includes("快速决策")) {
      weightedTypes.push("reaction", "attention");
    }
    if (selectedAI.specialties.includes("模式识别")) {
      weightedTypes.push("pattern", "spatial");
    }
  }

  const type = weightedTypes[Math.floor(Math.random() * weightedTypes.length)];
  const baseDifficulty = isTeamMode ? "medium" : "easy";
  const difficulty = Math.random() > 0.3 ? baseDifficulty : "hard";

  switch (type) {
    case "reaction":
      const reactionVariants = [
        "当看到绿色圆圈时点击！",
        "看到蓝色方块立即点击！",
        "红色信号出现时快速点击！",
        "当图标闪烁时点击按钮！",
      ];
      return {
        id: round,
        type: "reaction",
        category: "反应速度",
        difficulty,
        question: isTeamMode
          ? "团队反应测试：看到信号立即点击！"
          : reactionVariants[
              Math.floor(Math.random() * reactionVariants.length)
            ],
        correctAnswer: "click",
        completed: false,
      };

    case "memory":
      const length =
        difficulty === "easy"
          ? isTeamMode
            ? 4
            : 3
          : difficulty === "medium"
          ? isTeamMode
            ? 5
            : 4
          : isTeamMode
          ? 6
          : 5;

      const memoryTypes = [
        () => {
          // 数字记忆 - 选择单个正确数字
          const sequence = Array.from(
            { length },
            () => Math.floor(Math.random() * 9) + 1
          );
          const correctIndex = Math.floor(Math.random() * sequence.length);
          const correctItem = sequence[correctIndex];
          // 创建包含正确答案的选项，并添加其他数字作为干扰项
          const distractors = Array.from({ length: 3 }, () => {
            let num;
            do {
              num = Math.floor(Math.random() * 9) + 1;
            } while (sequence.includes(num));
            return num;
          });
          const allOptions = [...new Set([correctItem, ...distractors])]
            .map(String)
            .slice(0, 4);
          return {
            question: `记住数字序列：${sequence.join(" - ")}，第${
              correctIndex + 1
            }个数字是？`,
            options: allOptions,
            correctAnswer: correctItem.toString(),
          };
        },
        () => {
          // 颜色记忆 - 选择单个正确颜色
          const colors = ["红", "蓝", "绿", "黄", "紫", "橙"];
          const sequence = Array.from(
            { length: Math.min(length, 4) },
            () => colors[Math.floor(Math.random() * colors.length)]
          );
          const correctIndex = Math.floor(Math.random() * sequence.length);
          const correctItem = sequence[correctIndex];
          // 创建选项，包含序列中出现的颜色和一些干扰项
          const distractors = colors
            .filter((color) => !sequence.includes(color))
            .slice(0, 2);
          const allOptions = [
            ...new Set([correctItem, ...sequence.slice(0, 2), ...distractors]),
          ].slice(0, 4);
          return {
            question: `记住颜色序列：${sequence.join(" → ")}，第${
              correctIndex + 1
            }个颜色是？`,
            options: allOptions,
            correctAnswer: correctItem,
          };
        },
        () => {
          // 字母记忆 - 选择单个正确字母
          const letters = ["A", "B", "C", "D", "E", "F"];
          const sequence = Array.from(
            { length: Math.min(length, 4) },
            () => letters[Math.floor(Math.random() * letters.length)]
          );
          const correctIndex = Math.floor(Math.random() * sequence.length);
          const correctItem = sequence[correctIndex];
          // 创建选项
          const distractors = letters
            .filter((letter) => !sequence.includes(letter))
            .slice(0, 2);
          const allOptions = [
            ...new Set([correctItem, ...sequence.slice(0, 2), ...distractors]),
          ].slice(0, 4);
          return {
            question: `记住字母序列：${sequence.join(" - ")}，第${
              correctIndex + 1
            }个字母是？`,
            options: allOptions,
            correctAnswer: correctItem,
          };
        },
      ];
      const memoryChallenge =
        memoryTypes[Math.floor(Math.random() * memoryTypes.length)]();
      return {
        id: round,
        type: "memory",
        category: "记忆测试",
        difficulty,
        question: memoryChallenge.question,
        options: memoryChallenge.options,
        correctAnswer: memoryChallenge.correctAnswer,
        completed: false,
      };

    case "math":
      const mathTypes = [
        () => {
          const a =
            Math.floor(Math.random() * (difficulty === "hard" ? 100 : 50)) + 5;
          const b =
            Math.floor(Math.random() * (difficulty === "hard" ? 50 : 30)) + 5;
          const op = ["+", "-"][Math.floor(Math.random() * 2)];
          const result = op === "+" ? a + b : a - b;
          // 生成干扰选项
          const wrongOptions = [
            result + Math.floor(Math.random() * 10) + 1,
            result - Math.floor(Math.random() * 10) - 1,
            result + Math.floor(Math.random() * 5) + 5,
          ].filter((n) => n > 0 && n !== result);
          const allOptions = [result, ...wrongOptions.slice(0, 3)].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${a} ${op} ${b} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
        () => {
          const a = Math.floor(Math.random() * 12) + 2;
          const b =
            Math.floor(Math.random() * (difficulty === "hard" ? 12 : 8)) + 2;
          const result = a * b;
          // 生成干扰选项
          const wrongOptions = [
            result + a, // 常见错误：加法而不是乘法
            result - b, // 常见错误：减法
            (a + 1) * b, // 常见错误：a+1
            a * (b + 1), // 常见错误：b+1
          ].filter((n) => n > 0 && n !== result);
          const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
          const allOptions = [result, ...uniqueWrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${a} × ${b} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
        () => {
          const nums = Array.from(
            { length: 3 },
            () => Math.floor(Math.random() * 20) + 1
          );
          const result = nums.reduce((sum, num) => sum + num, 0);
          // 生成干扰选项
          const wrongOptions = [
            result + Math.floor(Math.random() * 5) + 1,
            result - Math.floor(Math.random() * 5) - 1,
            result + nums[0], // 常见错误：重复加第一个数
            result - nums[2], // 常见错误：减最后一个数
          ].filter((n) => n > 0 && n !== result);
          const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
          const allOptions = [result, ...uniqueWrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${nums.join(" + ")} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
        () => {
          const base = Math.floor(Math.random() * 8) + 2;
          const exp =
            difficulty === "hard" ? Math.floor(Math.random() * 3) + 3 : 2;
          const result = Math.pow(base, exp);
          // 生成干扰选项
          const wrongOptions = [
            base * exp, // 常见错误：乘法而不是乘方
            Math.pow(base, exp - 1), // 指数减1
            Math.pow(base - 1, exp), // 底数减1
            result + base, // 加上底数
          ].filter((n) => n > 0 && n !== result);
          const uniqueWrongOptions = [...new Set(wrongOptions)].slice(0, 3);
          const allOptions = [result, ...uniqueWrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `${base}^${exp} = ?`,
            answer: result.toString(),
            options: allOptions.map(String),
          };
        },
      ];
      const mathChallenge =
        mathTypes[Math.floor(Math.random() * mathTypes.length)]();
      return {
        id: round,
        type: "math",
        category: "数学计算",
        difficulty,
        question: mathChallenge.question,
        options: mathChallenge.options,
        correctAnswer: mathChallenge.answer,
        completed: false,
      };

    case "pattern":
      const patternTypes = [
        () => {
          const symbols = ["🔴", "🔵", "🟢", "🟡", "⭐", "🌙"];
          const patternLength = difficulty === "hard" ? 5 : 4;
          // 创建简单的交替模式
          const pattern = Array.from(
            { length: patternLength },
            (_, i) => symbols[i % 2]
          );
          const nextSymbol = symbols[patternLength % 2]; // 下一个应该是什么
          // 创建包含正确答案的选项
          const wrongOptions = symbols
            .filter((s) => s !== nextSymbol)
            .slice(0, 3);
          const allOptions = [nextSymbol, ...wrongOptions].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `找规律：${pattern.join(" ")} ?`,
            options: allOptions,
            answer: nextSymbol,
          };
        },
        () => {
          const sequences = [
            { nums: [2, 4, 6, 8], next: 10, rule: "+2" },
            { nums: [1, 3, 5, 7], next: 9, rule: "+2" },
            { nums: [2, 4, 8, 16], next: 32, rule: "×2" },
            { nums: [1, 2, 4, 8], next: 16, rule: "×2" },
            { nums: [10, 8, 6, 4], next: 2, rule: "-2" },
            { nums: [20, 16, 12, 8], next: 4, rule: "-4" },
          ];
          const selected =
            sequences[Math.floor(Math.random() * sequences.length)];
          const wrongOptions = [
            selected.next + 1,
            selected.next - 1,
            selected.next + 2,
          ].filter((n) => n !== selected.next && n > 0);
          const allOptions = [selected.next, ...wrongOptions.slice(0, 3)].sort(
            () => Math.random() - 0.5
          );
          return {
            question: `数列规律：${selected.nums.join(", ")} ?`,
            options: allOptions.map(String),
            answer: selected.next.toString(),
          };
        },
      ];
      const patternChallenge =
        patternTypes[Math.floor(Math.random() * patternTypes.length)]();
      return {
        id: round,
        type: "pattern",
        category: "模式识别",
        difficulty,
        question: patternChallenge.question,
        options: patternChallenge.options,
        correctAnswer: patternChallenge.answer,
        completed: false,
      };

    // ... (Add other cases: color, logic, word, etc. from the original file)
    default:
      return generateChallenge(round, isTeamMode, selectedAI); // Fallback to avoid errors
  }
};

export const generateAIAnswer = (challenge, selectedAI = null) => {
  let baseTime = 1000 + Math.random() * 2000;
  let difficultyMultiplier = 1 - (selectedAI?.difficulty || 0.5) * 0.5;
  let errorRate = 1 - (selectedAI?.difficulty || 0.5);

  if (selectedAI?.specialties) {
    const specialtyBonus = getSpecialtyBonus(
      challenge.category,
      selectedAI.specialties
    );
    difficultyMultiplier *= 1 - specialtyBonus * 0.3;
    errorRate *= 1 - specialtyBonus * 0.4;
  }

  const difficultyFactor =
    {
      easy: 0.8,
      medium: 1.0,
      hard: 1.3,
    }[challenge.difficulty] || 1.0;

  baseTime *= difficultyFactor;
  errorRate *= difficultyFactor;

  if (challenge.type === "reaction") {
    baseTime = 300 + Math.random() * 800;
    errorRate *= 0.5;
  }

  const actualTime = baseTime * difficultyMultiplier;
  const willMakeError = Math.random() < Math.min(0.4, errorRate);

  if (challenge.options && challenge.options.length > 0) {
    if (willMakeError) {
      const wrongOptions = challenge.options.filter(
        (opt) => String(opt) !== String(challenge.correctAnswer)
      );
      if (wrongOptions.length > 0) {
        return {
          answer: wrongOptions[Math.floor(Math.random() * wrongOptions.length)],
          time: actualTime,
        };
      }
    }

    if (challenge.options.includes(String(challenge.correctAnswer))) {
      return {
        answer: challenge.correctAnswer,
        time: actualTime,
      };
    } else {
      return {
        answer:
          challenge.options[
            Math.floor(Math.random() * challenge.options.length)
          ],
        time: actualTime,
      };
    }
  }

  if (willMakeError && typeof challenge.correctAnswer === "number") {
    const deviation = Math.floor(Math.random() * 10) + 1;
    const wrongAnswer =
      Math.random() > 0.5
        ? challenge.correctAnswer + deviation
        : Math.max(0, challenge.correctAnswer - deviation);
    return {
      answer: wrongAnswer,
      time: actualTime,
    };
  }

  return {
    answer: challenge.correctAnswer,
    time: actualTime,
  };
};

const getSpecialtyBonus = (category, specialties) => {
  const categoryMapping = {
    反应速度: ["基础反应", "快速决策", "反应速度", "动作协调"],
    记忆测试: ["基础反应", "简单逻辑"],
    数学计算: ["简单逻辑", "策略规划"],
    计算应用: ["简单逻辑", "策略规划"],
    模式识别: ["逻辑推理", "策略规划", "模式识别"],
    颜色识别: ["基础反应", "模式识别"],
    逻辑推理: ["逻辑推理", "策略规划", "适应性学习"],
    语言理解: ["逻辑推理", "适应性学习"],
    序列推理: ["逻辑推理", "模式识别", "策略规划"],
    空间推理: ["模式识别", "策略规划"],
    注意力测试: ["快速决策", "反应速度", "完美执行"],
    比较分析: ["策略规划", "适应性学习"],
  };

  const relevantSpecialties = categoryMapping[category] || [];
  const matchCount = specialties.filter((specialty) =>
    relevantSpecialties.some(
      (relevant) => specialty.includes(relevant) || relevant.includes(specialty)
    )
  ).length;

  return Math.min(1.0, matchCount * 0.5);
};